import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { FaSearch, FaFilter, FaSync, FaExchangeAlt } from 'react-icons/fa';
import '../styles/PersonnelList.css';

const PersonnelList = () => {
  const [personnel, setPersonnel] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [organizations, setOrganizations] = useState([]);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 20,
    total: 0,
    pages: 0
  });
  
  // 筛选条件
  const [filters, setFilters] = useState({
    organization: '',
    positionChangeStatus: '',
    search: '',
    sortBy: 'lastUpdated',
    order: 'desc'
  });

  // 获取人员列表
  const fetchPersonnel = async (page = 1) => {
    try {
      setLoading(true);
      
      const params = {
        page,
        limit: pagination.limit,
        ...filters
      };
      
      const res = await axios.get('/api/personnel', { params });
      setPersonnel(res.data.personnel);
      setPagination(res.data.pagination);
      setError(null);
    } catch (err) {
      console.error('获取人员列表失败:', err);
      setError('获取人员列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  // 获取组织列表
  const fetchOrganizations = async () => {
    try {
      const res = await axios.get('/api/personnel/organizations/list');
      setOrganizations(res.data);
    } catch (err) {
      console.error('获取组织列表失败:', err);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchPersonnel();
    fetchOrganizations();
  }, []);

  // 筛选条件变化时重新加载
  useEffect(() => {
    fetchPersonnel(1);
  }, [filters]);

  // 处理筛选条件变化
  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters(prev => ({ ...prev, [name]: value }));
  };

  // 处理搜索
  const handleSearch = (e) => {
    e.preventDefault();
    // 搜索已经通过 useEffect 触发了重新加载
  };

  // 处理排序
  const handleSort = (field) => {
    if (filters.sortBy === field) {
      // 切换排序顺序
      setFilters(prev => ({ 
        ...prev, 
        order: prev.order === 'asc' ? 'desc' : 'asc' 
      }));
    } else {
      // 设置新的排序字段
      setFilters(prev => ({ 
        ...prev, 
        sortBy: field, 
        order: 'asc' 
      }));
    }
  };

  // 处理分页
  const handlePageChange = (newPage) => {
    if (newPage < 1 || newPage > pagination.pages) return;
    fetchPersonnel(newPage);
  };

  // 获取职位变更状态的文字和样式
  const getPositionChangeStatus = (person) => {
    if (!person.positionChangeStatus) return { text: '无变化', className: 'no-change' };
    
    switch (person.positionChangeStatus) {
      case 'new':
        return { text: '新任命', className: 'new-position' };
      case 'replaced':
        return { text: '被替换', className: 'replaced' };
      case 'replacement':
        return { text: '接替者', className: 'replacement' };
      case 'position_changed':
        return { text: '职位变动', className: 'position-changed' };
      default:
        return { text: '无变化', className: 'no-change' };
    }
  };

  return (
    <div className="personnel-list-container">
      <div className="page-header">
        <h1>人员信息</h1>
      </div>

      {error && <div className="error-message">{error}</div>}

      {/* 筛选器 */}
      <div className="filters">
        <form onSubmit={handleSearch} className="search-form">
          <div className="search-input">
            <input
              type="text"
              name="search"
              value={filters.search}
              onChange={handleFilterChange}
              placeholder="搜索人员姓名或职位..."
            />
            <button type="submit" className="search-button">
              <FaSearch />
            </button>
          </div>
        </form>

        <div className="filter-options">
          <div className="filter-group">
            <label>组织:</label>
            <select
              name="organization"
              value={filters.organization}
              onChange={handleFilterChange}
            >
              <option value="">所有组织</option>
              {organizations.map(org => (
                <option key={org} value={org}>{org}</option>
              ))}
            </select>
          </div>

          <div className="filter-group">
            <label>职位变更状态:</label>
            <select
              name="positionChangeStatus"
              value={filters.positionChangeStatus}
              onChange={handleFilterChange}
            >
              <option value="">所有状态</option>
              <option value="new">新任命</option>
              <option value="replaced">被替换</option>
              <option value="replacement">接替者</option>
              <option value="position_changed">职位变动</option>
            </select>
          </div>

          <button 
            onClick={() => fetchPersonnel(pagination.page)} 
            className="refresh-button"
            title="刷新"
          >
            <FaSync />
          </button>
        </div>
      </div>

      {/* 人员列表 */}
      {loading && personnel.length === 0 ? (
        <div className="loading">加载中...</div>
      ) : personnel.length > 0 ? (
        <div className="personnel-table-container">
          <table className="personnel-table">
            <thead>
              <tr>
                <th className="image-cell">照片</th>
                <th 
                  className={`sortable ${filters.sortBy === 'name' ? 'active-sort' : ''}`}
                  onClick={() => handleSort('name')}
                >
                  姓名
                  {filters.sortBy === 'name' && (
                    <span className="sort-indicator">
                      {filters.order === 'asc' ? '↑' : '↓'}
                    </span>
                  )}
                </th>
                <th>职位</th>
                <th 
                  className={`sortable ${filters.sortBy === 'organization' ? 'active-sort' : ''}`}
                  onClick={() => handleSort('organization')}
                >
                  组织
                  {filters.sortBy === 'organization' && (
                    <span className="sort-indicator">
                      {filters.order === 'asc' ? '↑' : '↓'}
                    </span>
                  )}
                </th>
                <th>职位变更</th>
                <th 
                  className={`sortable ${filters.sortBy === 'positionChangeDate' ? 'active-sort' : ''}`}
                  onClick={() => handleSort('positionChangeDate')}
                >
                  变更日期
                  {filters.sortBy === 'positionChangeDate' && (
                    <span className="sort-indicator">
                      {filters.order === 'asc' ? '↑' : '↓'}
                    </span>
                  )}
                </th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {personnel.map(person => {
                const positionStatus = getPositionChangeStatus(person);
                return (
                <tr key={person._id}>
                  <td className="image-cell">
                    {person.imageUrl ? (
                      <img 
                        src={person.imageUrl} 
                        alt={person.name} 
                        className="personnel-image" 
                      />
                    ) : (
                      <div className="image-placeholder">无图片</div>
                    )}
                  </td>
                  <td>{person.name}</td>
                  <td>{person.position || '未知'}</td>
                  <td>{person.organization}</td>
                  <td>
                    <span className={`position-status ${positionStatus.className}`}>
                      {person.positionChangeStatus && <FaExchangeAlt className="change-icon" />}
                      {positionStatus.text}
                    </span>
                  </td>
                  <td>{person.positionChangeDate ? new Date(person.positionChangeDate).toLocaleString() : '无变更'}</td>
                  <td>
                    <Link to={`/personnel/${person._id}`} className="view-button">
                      查看详情
                    </Link>
                  </td>
                </tr>
              )})}
            </tbody>
          </table>

          {/* 分页 */}
          {pagination.pages > 1 && (
            <div className="pagination">
              <button 
                onClick={() => handlePageChange(1)} 
                disabled={pagination.page === 1}
                className="page-button"
              >
                首页
              </button>
              <button 
                onClick={() => handlePageChange(pagination.page - 1)} 
                disabled={pagination.page === 1}
                className="page-button"
              >
                上一页
              </button>
              <span className="page-info">
                {pagination.page} / {pagination.pages}
              </span>
              <button 
                onClick={() => handlePageChange(pagination.page + 1)} 
                disabled={pagination.page === pagination.pages}
                className="page-button"
              >
                下一页
              </button>
              <button 
                onClick={() => handlePageChange(pagination.pages)} 
                disabled={pagination.page === pagination.pages}
                className="page-button"
              >
                末页
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="no-data">
          没有找到符合条件的人员信息
        </div>
      )}
    </div>
  );
};

export default PersonnelList; 